/**
 * Created by Su on 2014/11/18.
 */


/**
 * 替换选中的文本
 * @param {jquery-object} $o
 * @param {String} str
 * @returns {void}
 * @example replaceSelection($(this).parent().find('textarea'), 'abc');
 * @since 1.0 2014-7-3 by sutroon
 */
function replaceSelection($o, str) {
    var _o = $o.get(0);
    if (!_o)
        return;
    if (checkBrowser() == 'IE') {
        _o.focus();
        var sel = document.selection.createRange();
        sel.text = str;
        sel.select();
    } else if (_o.selectionStart || _o.selectionStart == '0') {
        var startPos = _o.selectionStart;
        var endPos = _o.selectionEnd;
        var restoreTop = _o.scrollTop;
        _o.value = _o.value.substring(0, startPos) + str + _o.value.substring(endPos, _o.value.length);
        if (restoreTop > 0) {
            _o.scrollTop = restoreTop;
        }
        _o.focus();
        _o.selectionStart = startPos + str.length;
        _o.selectionEnd = startPos + str.length;
    }
}

/**
 * 检测浏览器类型
 * @returns {String}
 * @since 1.0 2014-7-3 by sutroon
 */
function checkBrowser() {
    var browserName = navigator.userAgent.toLowerCase();
    if (/msie/i.test(browserName) && !/opera/.test(browserName)) {
        return "IE";
    } else if (/firefox/i.test(browserName)) {
        return "Firefox";
    } else if (/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName)) {
        return "Chrome";
    } else if (/opera/i.test(browserName)) {
        return "Opera";
    } else if (/webkit/i.test(browserName) && !(/chrome/i.test(browserName) && /webkit/i.test(browserName) && /mozilla/i.test(browserName))) {
        return "Safari";
    } else {
        return 'unKnow';
    }
}
/**
 * 切换显示ajax加载效果
 * @param {boolean} display 显示或隐藏
 * @param {boolean} maskpage 是否遮罩整个页面
 * @returns {undefined}
 * @since 1.0 2014-6-17 created; 1.1 2014-10-6 by sutroon 新增loc,maskflag位置参数; 1.2 2014-11-3 by sutroon 修正全局(包括iframe)只会在顶层窗口有一个loading效果; 1.3 2015-3-16 by sutroon 精简重构
 */
function toggle_ajax_loading(display, maskpage) {
    var $body = window.parent ? $('body', window.parent.document) : $('body', document);
    var loading = '';
    if (maskpage) {
        loading = "<div id='soajax-loading' style='position:absolute;left:0;width:100%;height:100%;top:0;background:#FFFFFF;opacity:0.8;filter:alpha(opacity=90);z-index:9999999;'>";
        loading += "<div style='border:2px solid #B7CDFC;cursor:pointer;position:relative;top:45%;margin:0 auto;width:200px;height:36px;line-height:36px;font-size:12px;background:#fff;text-align:center;'>";
    } else {
        loading = "<div id='soajax-loading' style='position:absolute;left:45%;width:200px;height:36px;top:45%;background:#FFFFFF;opacity:0.8;filter:alpha(opacity=90);z-index:9999999;'>";
        loading += "<div style='border:2px solid #B7CDFC;cursor:pointer;margin:0 auto;width:200px;height:36px;line-height:36px;font-size:12px;background:#fff;text-align:center;'>";
    }
    loading += "正在读取数据，请稍后...</div></div>";
    if (display) {
        $body.append(loading);
    } else {
        if (undefined != $body.find("#soajax-loading")) {
            $body.find("#msoajax-loading").remove();
        }
    }
}

/**
 * 加载select控件的options
 * @param {string} selector 选择器
 * @param {string} uri ajax数据源地址
 * @param {string} def_option 默认第一行显示的文本,如:请选择...
 * @param {string} value 默认值
 * @param {string} perpends 添加的额外options,如果加前缀+则追加到后面,默认追加到前面
 * @param {function} func ajax加载完成后执行的方法
 * @returns {void}
 * @since 1.0 2014-6-17 by sutroon
 *      1.1 2014-7-16 by sutroon 新增如果控件不存在则跳出方法的逻辑
 *      1.2 2014-8-22 by sutroon 新增对树形数据的支持
 * @example 
 *      ajax_load_options('select[name="tbRoleID"]', '?s=Role/get_options/jsonpReturn/?', '请选择角色');
 *      var strQueueOpts = ajax_load_options('', '?s=AcdNo/get_queue_json.html', '选择队列号码', '{$data.queue}', '&lt;option value=""&gt;新增项&lt;/option&gt;', afterQueue);
 */
function ajax_load_options(selector, uri, def_option, value, prepends, func) {
    if (!func && !$(selector)[0]) {
        return;
    }
    $.getJSON(uri, function (data) {
        if (selector) {
            $(selector).empty();
        }
        if (!data) {
            return;
        }
        var $data = (typeof (data) == "object") ? data : $.parseJSON(data);
        var str = '';
        str = generate_options($data);
        if (prepends) {
            if (prepends[0] == '+') {
                str += prepends;
            } else {
                str = prepends + str;
            }
        }
        if (def_option) { // 添加默认选项到第一行
            str = '<option value="">' + def_option + '</option>' + str;
        }
        if (selector) {
            $(selector).html(str);
        }
        if (value && selector) {
            if (value.length > 4 && value.substring(0, 4) == 'TXT:') {
                $(selector).find('option:contains("' + value.substring(4) + '")').prop('selected', true);
            } else {
                $(selector).find('option[value="' + value + '"]').prop('selected', true);
            }
            str = $(selector).html();
        }
        // 如果有定义函数则执行
        if (func) {
            func(str);
        }
    });
}

/**
 * 根据json数据生成option树形控件
 * 如果有children节点则自动生成树形数据
 * @param {JSON} data
 * @param {int} n 节点深度
 * @param {string} char 节点名称前缀
 * @returns {string}
 * @since 1.0 2014-8-22 by sutroon
 * @example
 *      var data = (typeof (data) == "object") ? data : $.parseJSON(data);
 *      var str = '';
 *      str=generate_options(data);
 */
function generate_options(data, n, char) {
    if (n == undefined) {
        n = 0;
    }
    if (char == undefined) {
        char = '..';
    }
    var pad = '';
    while (n > 0) {
        pad += char;
        n--;
    }
    var str = '';
    if (data.length) {
        // 多行格式
        for (var i = 0; i < data.length; i++) {
            if (data[i].id) {
                // 用于[{"id":"1","name":"name1"}]格式                
                str += '<option value="' + data[i].id + '">' + pad + (data[i].name ? data[i].name : data[i].text) + '</option>';
            } else if (data[i].item) {
                // 用于[{"item":"1"},{"item":"2"}]
                str += '<option value="' + data[i].item + '">' + pad + data[i].item + '</option>';
            } else {
                // 用于{"item1","item2"}格式
                str += '<option value="' + data[i] + '">' + pad + data[i] + '</option>';
            }
            if (data[i].children) {
                str += generate_options(data[i].children, n + 1, char);
            }
        }
    }
    else {
        // 用于{"a":"a1","b":"b2"}单行格式
        for (var attr in data) {
            str += '<option value="' + attr + '">' + data[attr] + '</option>';
        }
    }
    return str;
}

/**
 * 获取json数据对象的键值
 * @param {json} jsonObject
 * @returns {array}
 * @since 1.0 2014-12-23 by sutroon
 */
function get_json_keys(jsonObject) {
    var keys = [];
    for (var p in jsonObject) {
        if (jsonObject.hasOwnProperty(p)) {
            keys.push(p);
        }
    }
    return keys;
}

/**
 * Eggs ^_^
 * @since 1.0 2014-9-27 by sutroon
 */
function setEggs() {
    var eggs_i = 0;
    $('.eggs').click(function () {
        eggs_i++;
        if (eggs_i >= 5) {
            document.write('hello, sutroon! <a href="#" onclick="history.back();">[返回]</a><div style="color:#FFF;">2014年9月26号是我人生的转折点,感谢公司和领导的支持,所以利用在XCall改版之际,全心全意把XCall做得最好!<br />2014-9-27 by sutroon(14507247@qq.com) </div>');
        }
    })
}

/**
 * 时钟功能
 * @returns {void}
 * @since 1.0 2014-8-15 by sutroon
 */
function clock() {
    var date = new Date();
    var arrdate = [date.getMinutes(), date.getSeconds()];
    var text = (arrdate[0] < 10 ? '0' + arrdate[0] : arrdate[0]) + ':' + (arrdate[1] < 10 ? '0' + arrdate[1] : arrdate[1]);
    var h = date.getHours();
    var w = '';
    if (h < 5) {
        w = '凌晨了,注意身体,早点休息哦!';
    } else if (h >= 5 && h < 11) {
        w = '早上好,一日之计在于晨,加油哦^_^';
    } else if (h > 14 && h < 18) {
        w = '下午好,保持愉快心情努力工作哦~';
    } else if (h > 18 && h < 21) {
        w = '晚上好!';
    } else if (h >= 21 && h < 24) {
        w = '夜深了,还没休息啊!';
    }
    var week = ['日', '一', '二', '三', '四', '五', '六'];
    var title = (date.getMonth() + 1) + '月' + date.getDate() + '日 周' + week[date.getDay()] + ' ' + date.getHours() + ':' + arrdate[0] + '<br />' + w;
    $('#head-clock').attr('title', title).text(text);
}


/**
 * 返回本月的最大天数
 * @param {Integer} iMonth
 * @param {Integer} iYear
 * @returns {Integer}
 * @since 1.0 2015-3-19 by sutroon
 */
function daysInMonth2(iMonth, iYear) {
    return 32 - new Date(iYear, iMonth, 32).getDate();
}

/**
 * 返回本月的最大天数
 * @param {Date} date
 * @returns {Integer}
 * @since 1.0 2015-3-19 by sutroon
 */
function daysInMonth(date) {
    return 32 - new Date(date.getYear(), date.getMonth(), 32).getDate();
}

function dateToString(date) {
    var _todayDate = date.getDate();
    var _year = date.getYear();
    !document.addEventListener || (_year += 1900);
    var _month = date.getMonth() + 1;
    return _year + "-" + _month + "-" + _todayDate;
}

/**
 * 判断是否闰年
 * @param {Integer} year
 * @returns {Boolean}
 * @since 1.0 2015-3-19 by sutroon
 */
function isLeapYear(year) {
    if (!isNaN(parseInt(year))) {
        return false;
    }
    return ((year % 4 == 0 && year % 100 != 0) || (year % 100 == 0 && year % 400 == 0));
}


/**
 * 获取前天、昨天、今天、明天、后天的时间
 * @param {Integer} n
 * @returns {string}
 * @since 1.0 2015-3-19 by sutroon
 * @example 
 * var dayDateTester={'前天':-2,'昨天':-1,'今天':0,'明天':1,'后天':2,'大后天':3};
 * var str='';    
 * for (var p in dayDateTester) {
 *      str += p + '=' + dayDate(dayDateTester[p]) + '\n';
 * }
 * alert(str);
 */
function dayDate(n) {
    var dd = new Date();
    dd.setDate(dd.getDate() + n);
    return dateToString(dd);
}

/**
 * 字符串转换为日期对象
 * @param {String} strTime
 * @returns {null|Date} 成功则返回Date对象，否则返回null
 * @since 1.0 2015-3-19 by sutroon
 */
function strToDate(strTime) {
    var n = Date.parse(strTime.replace(/-/g, "/"));
    return isNaN(n) ? null : new Date(n);
}

/**
 * 获取本周，本月，本季，本年，上月，上周，上季，去年，上二周，上二月的时间段
 * @param {String} name 名称
 * @param {JSON} options 选项
 *      String:date 基础日期
 *      Integer:int 变动数量
 *      String:type 算法类型 NORMAL=普通日历算法,FRONT=从今天向前推演,如2015-03-18本周应该是03-16至03-22,如果是FRONT则为03-12值03-18
 * @returns {Array}
 * @since 1.0 2015-3-19 by sutroon
 * @example
 * var dateRangeTester = {'本周': 'week', '本月': 'month', '本季': 'quarter', '本年': 'year', '上周': 'pweek', '上月': 'pmonth', '上季': 'pquarter', '去年': 'pyear', '上二周': 'p2week', '上二月': 'p2month'};
 * var str = '';
 * for (var p in dateRangeTester) {
 *      str += p + '=' + dateRange(dateRangeTester[p]) + '\n';
 * }
 * alert(str);
 */
function dateRange(name, options) {
    var opts = {'date': null, 'inc': null, 'type': 'FRONT'};
    opts = $.extend({}, opts, options);
    var beginTime;
    var endTime;
    var now = null;
    if (opts.date) {
        now = strToDate(opts.date);
    }
    if (!now) {
        now = new Date();
    }
    var objnow = {'month': now.getMonth(), 'year': now.getFullYear(), 'day': now.getDate(), 'wday': now.getDay()};
    switch (name) {
        case "week": //本周
            switch (opts.type) {
                case 'FRONT':
                    now.setDate(now.getDate() - 6);
                    break;
                default:
                    var day = now.getDay();
                    now.setDate(now.getDate() - (day - 1));
                    break;
            }
            beginTime = dateToString(now);

            now.setDate(now.getDate() + 6);
            endTime = dateToString(now);
            break;
        case "month":  //本月
            now.setDate(1);
            beginTime = dateToString(now);

            var days = daysInMonth(now);
            now.setDate(days);
            endTime = dateToString(now);
            break;
        case "quarter":   //本季
            var m = now.getMonth() + 1;
            var q = parseInt((m + 2) / 3); //得到第几季
            m = q * 3 - 2;  //得到季的首月份

            now.setMonth(m - 1);
            now.setDate(1);
            beginTime = dateToString(now);

            now.setMonth(now.getMonth() + 3);
            now.setDate(0);
            endTime = dateToString(now);
            break;
        case "year":    //本年
            now.setMonth(0);
            now.setDate(1);
            beginTime = dateToString(now);

            now.setMonth(11);
            now.setDate(31);
            endTime = dateToString(now);
            break;
        case "pweek":    //上周
            var day = now.getDay();
            now.setDate(now.getDate() - (day - 1) - 7);
            beginTime = dateToString(now);

            now.setDate(now.getDate() + 6);
            endTime = dateToString(now);

            break;
        case "pmonth":    //上月
            now.setDate(1);
            now.setMonth(now.getMonth() - 1);
            beginTime = dateToString(now);

            var days = daysInMonth(now);
            now.setDate(days);
            endTime = dateToString(now);
            break;
        case "pquarter":    //上季
            var m = now.getMonth() + 1;
            var q = parseInt((m + 2) / 3); //得到第几季
            m = q * 3 - 2;  //得到季的首月份

            m = m - 3; //上季
            now.setMonth(m - 1);
            now.setDate(1);
            beginTime = dateToString(now);

            now.setMonth(now.getMonth() + 3);
            now.setDate(0);
            endTime = dateToString(now);
            break;
        case "pyear":    //去年
            now.setFullYear(now.getFullYear() - 1);
            now.setMonth(0);
            now.setDate(1);
            beginTime = dateToString(now);

            now.setMonth(11);
            now.setDate(31);
            endTime = dateToString(now);
            break;
        case "p2week":    //上二周
            var day = now.getDay();
            now.setDate(now.getDate() - (day - 1) - 7 * 2);
            beginTime = dateToString(now);

            now.setDate(now.getDate() + 6 + 7);
            endTime = dateToString(now);
            break;
        case "p2month":    //上二月
            now.setDate(1);
            now.setMonth(now.getMonth() - 1 * 2);
            beginTime = dateToString(now);

            now.setMonth(now.getMonth() + 2);
            now.setDate(0);
            endTime = dateToString(now);
            break;
        case "customize":    //自定义
            beginTime = "";
            endTime = "";
            break;
    }
    return [beginTime, endTime];
}
/**
 * html5文件预览功能
 * @since 1.0 <2015-3-27> SoChishun Added.
 */
function html5_file_preview() {
    $('[type=file]').change(function (e) {
        var file = e.target.files[0];
        var url = URL.createObjectURL(file);
        var $file = $(this);
        var $img = $file.next('img.preview');
        if ($img[0] && 'IMG' == $img[0].tagName) {
            $img.attr('src', url);
        } else {
            $file.after('<img class="preview" src="' + url + '" style="max-width: 60px;max-height:60px;" />')
        }
    })
}